<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告 -->
      <el-alert
        title="只允许第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择 -->
          <el-cascader
            v-model="selectCatKeys"
            :options="catList"
            :props="propConfig"
            clearable
            @change="selectCatKeysChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页 -->
      <el-tabs v-model="activeName" @tab-click="tabHandleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isDisable" @click="addOpen">
            添加参数
          </el-button>
          <!-- many表格 -->
          <el-table :data="manyData" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editAttrOpen(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delAttr(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isDisable" @click="addOpen">
            添加属性
          </el-button>
          <!-- only表格 -->
          <el-table :data="onlyData" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editAttrOpen(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delAttr(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数 -->
      <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="addDialogClose"
      >
        <el-form
          :model="addForm"
          ref="addForm"
          label-width="100px"
          :rules="addRules"
          class="demo-ruleForm"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveAttrs">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑参数 -->
      <el-dialog
        :title="'编辑' + titleText"
        :visible.sync="editDialogVisible"
        width="30%"
        @close="editDialogClose"
      >
        <el-form
          :model="editForm"
          ref="editForm"
          label-width="100px"
          :rules="addRules"
          class="demo-ruleForm"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input
              v-model="editForm.attr_name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEditAttrs">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import { categoryList, manyParams, addAttr, editAttr, deleteAttr, addAttrVals } from '@/api/categories'
import { addAttrValidate } from '@/validate/validate'
export default {
  name: 'Params',
  data() {
    return {
      catList: [],
      selectCatKeys: [],
      propConfig: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      activeName: 'many',
      manyData: [],
      onlyData: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      editForm: {
        attr_name: '',
        attr_id: ''
      },
      addRules: {
        attr_name: [
          { required: true, validator: addAttrValidate, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCatList()
  },
  computed: {
    isDisable() {
      if (this.selectCatKeys.length !== 3) {
        return true
      }
      return false
    },
    cateId() {
      if (this.selectCatKeys.length === 3) {
        return this.selectCatKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  methods: {
    async getCatList() {
      const { data: res } = await categoryList()
      this.catList = res.data
    },
    selectCatKeysChange() {
      // 只能选择三级标签
      this.getParams()
    },
    tabHandleClick() {
      this.getParams()
    },
    async getParams() {
      if (this.selectCatKeys.length !== 3) {
        this.selectCatKeys = []
        this.manyData = []
        this.onlyData = []
        return
      }
      // 获取对应tab的参数
      const params = {
        id: this.cateId,
        sel: this.activeName
      }
      const { data: res } = await manyParams(params)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      if (this.activeName === 'many') {
        res.data.map(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        this.manyData = res.data
      } else {
        res.data.map(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        this.onlyData = res.data
      }
    },
    addOpen() {
      this.addDialogVisible = true
    },
    saveAttrs() {
      this.$refs.addForm.validate(valid => {
        this.$refs.addForm.validate(async (valid) => {
          if (!valid) return
          const params = {
            id: this.cateId,
            data: {
              attr_sel: this.activeName,
              attr_name: this.addForm.attr_name
            }
          }
          const { data: res } = await addAttr(params)
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.getParams()
          this.addDialogClose()
        })
      })
    },
    addDialogClose() {
      this.$refs.addForm.resetFields()
      this.addDialogVisible = false
    },
    editAttrOpen(row) {
      this.editForm.attr_name = row.attr_name
      this.editForm.attr_id = row.attr_id
      console.log(this.editForm)
      this.editDialogVisible = true
    },
    saveEditAttrs() {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return
        const params = {
          catId: this.cateId,
          attr_id: this.editForm.attr_id,
          data: {
            attr_sel: this.activeName,
            attr_name: this.editForm.attr_name
          }
        }
        const { data: res } = await editAttr(params)
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getParams()
        this.editDialogClose()
      })
    },
    editDialogClose() {
      this.$refs.editForm.resetFields()
      this.editDialogVisible = false
    },
    async delAttr(row) {
      console.log(row)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const params = {
          catId: row.cat_id,
          attr_id: row.attr_id
        }
        const { data: res } = await deleteAttr(params)
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getParams()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async handleInputConfirm(row) {
      // 判断焦点失去或者enter后是否有值
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      // 本地显示
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.updataAttrsVals(row)
    },
    async updataAttrsVals(row) {
      // 有输入值就可以发生请求了
      const params = {
        catId: row.cat_id,
        attr_id: row.attr_id,
        data: {
          attr_sel: row.attr_sel,
          attr_name: row.attr_name,
          attr_vals: row.attr_vals.join(' ')
        }
      }
      const { data: res } = await addAttrVals(params)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    showInput(row) {
      row.inputVisible = true
      // 更新dom后操作
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除tag
    handleClose(index, row) {
      console.log(row)
      row.attr_vals.splice(index, 1)
      this.updataAttrsVals(row)
    }
  }

}
</script>
<style lang='less' scoped>
.cat_opt {
  margin: 15px 10px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  margin: 10px;
  width: 120px;
}
</style>
